import "package:ct_pa_majordomo/pages/mine/apartment_manage/water_electricity_setting/api.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import 'package:flutter/material.dart';
import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/widgets/button/index.dart';
import 'package:ct_pa_majordomo/widgets/tai_dialog/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:ct_pa_majordomo/pages/device/electricity_meter/api.dart';

class RechargePage extends StatefulWidget {
  final Map arguments;

  const RechargePage({Key? key, required this.arguments}) : super(key: key);

  @override
  State<RechargePage> createState() => _RechargePageState();
}

class _RechargePageState extends State<RechargePage> {
  final List<int> _amounts = [50, 100, 200, 500, 1000];
  int? _selectedAmount;
  final TextEditingController _customAmountController = TextEditingController();
  bool _isCustom = false;
  List _meterList = [];
  Map? _selectedMeter;

  late Map _priceConfig = {};


  // 获取电费单价配置
  void _getPriceConfig() async {
    Map resData = await waterElectricitySettingApi.getConfigInfo();
    setState(() {
      _priceConfig = resData["data"] ?? {};
    });
  }

  // 剩余度数换算
  double _convertRemainAmount(double remainAmount, double singlePrice) {
    if (remainAmount == 0 || remainAmount == null) {
      return 0;
    }

    if (singlePrice == 0 || singlePrice == null) {
      return 0;
    }

    return remainAmount / singlePrice;
  }
  
  @override
  void initState() {
    super.initState();
    _getPriceConfig();
    _selectedAmount = _amounts[0];
    _fetchMeterList("");
  }

  Future<void> _fetchMeterList(String number) async {
    try {
      Map resData = await electricityMeterApi.getElectricityMeterList({
        "roomId": widget.arguments['roomId']
      });
      print(resData);
      setState(() {
        _meterList = resData["rows"] ?? [];
        if (_meterList.isNotEmpty) {
          if (number != "") {
            _selectedMeter = _meterList.firstWhere((meter) => meter["number"] == number);
          } else {
            _selectedMeter = _meterList[0];
          }
        }
      });
    } catch (e) {
      EasyLoading.showError(e.toString());
    }
  }

  void _showMeterSelector() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.only(bottom: 16),
                decoration: const BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: ThemeVars.colorBorder,
                      width: 0.5,
                    ),
                  ),
                ),
                child: const Text(
                  "选择电表",
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              ..._meterList.map((meter) => GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  setState(() {
                    _selectedMeter = meter;
                  });
                  Navigator.pop(context);
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(meter['name'] ?? ''),
                      ),
                      if (_selectedMeter?['electricityMeterId'] == meter['electricityMeterId'])
                        const Icon(Icons.check, color: ThemeVars.colorPrimary)
                    ],
                  ),
                ),
              )).toList(),
            ],
          ),
        );
      }
    );
  }

  @override
  Widget build(BuildContext context) {
    String title = widget.arguments['type'] == 'electricity' ? '电费充值' : '水费充值';
    
    return NormalScaffold(
      title: title,
      child: Stack(
        children: [
          SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.all(ThemeVars.paddingPage),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "${widget.arguments['buildingName']} ${widget.arguments['roomName']}",
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500
                        ),
                      ),
                      GestureDetector(
                        onTap: _showMeterSelector,
                        child: Row(
                          children: [
                            Text(
                              _selectedMeter?['name'] ?? '',
                              style: const TextStyle(
                                fontSize: 14,
                                color: ThemeVars.colorTextSec
                              ),
                            ),
                            const Icon(
                              Icons.keyboard_arrow_down,
                              size: 16,
                              color: ThemeVars.colorTextSec,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(ThemeVars.paddingPage),
                  padding: const EdgeInsets.all(ThemeVars.paddingPage),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        "剩余电量",
                        style: TextStyle(
                          color: ThemeVars.colorTextSec,
                          fontSize: 14,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "${_convertRemainAmount(_selectedMeter?['remainAmount'] ?? 0, _priceConfig["kwhPrice"] ?? 0)}度",
                            style: const TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            "单价：¥${_priceConfig["kwhPrice"] ?? "0.00"}/度",
                            style: TextStyle(
                              color: ThemeVars.colorTextSec,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: const EdgeInsets.all(ThemeVars.paddingPage),
                  child: Wrap(
                    spacing: 12,
                    runSpacing: 12,
                    children: [
                      ..._amounts.map((amount) => _buildAmountItem(amount)),
                      _buildCustomAmountItem(),
                    ],
                  ),
                ),
                // 添加底部按钮的占位空间
                const SizedBox(height: 80),
              ],
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.all(ThemeVars.paddingPage),
              decoration: const BoxDecoration(
                border: Border(
                  top: BorderSide(
                    color: ThemeVars.colorBorder,
                    width: 0.5,
                  ),
                ),
              ),
              child: Button(
                type: ButtonType.primary,
                size: ButtonSize.large,
                onPressed: _handleRecharge,
                child: Text("${title}充值"),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAmountItem(int amount) {
    bool isSelected = !_isCustom && _selectedAmount == amount;
    
    return GestureDetector(
      onTap: () {
        setState(() {
          _isCustom = false;
          _selectedAmount = amount;
        });
      },
      child: Container(
        width: (MediaQuery.of(context).size.width - ThemeVars.paddingPage * 4) / 3,
        padding: const EdgeInsets.symmetric(vertical: 12),
        decoration: BoxDecoration(
          color: isSelected ? ThemeVars.colorPrimaryLight : ThemeVars.colorBackground,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: isSelected ? ThemeVars.colorPrimary : ThemeVars.colorBorder,
          ),
        ),
        child: Center(
          child: Text(
            "¥$amount",
            style: TextStyle(
              color: isSelected ? ThemeVars.colorPrimary : ThemeVars.colorTextSec,
              fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildCustomAmountItem() {
    return GestureDetector(
      onTap: () {
        setState(() {
          _isCustom = true;
          _selectedAmount = null;
        });
      },
      child: Container(
        width: (MediaQuery.of(context).size.width - ThemeVars.paddingPage * 4) / 3,
        padding: const EdgeInsets.symmetric(vertical: 12),
        decoration: BoxDecoration(
          color: _isCustom ? ThemeVars.colorPrimaryLight : ThemeVars.colorBackground,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: _isCustom ? ThemeVars.colorPrimary : ThemeVars.colorBorder,
          ),
        ),
        child: Center(
          child: _isCustom
              ? SizedBox(
                  width: 60,
                  child: TextField(
                    controller: _customAmountController,
                    textAlign: TextAlign.center,
                    keyboardType: TextInputType.number,
                    decoration: const InputDecoration(
                      isDense: true,
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      hintText: "输入金额",
                    ),
                  ),
                )
              : const Text("自定义"),
        ),
      ),
    );
  }

  void _handleRecharge() async {
    int amount = _isCustom
        ? int.tryParse(_customAmountController.text) ?? 0
        : _selectedAmount ?? 0;

    if (amount <= 0) {
      EasyLoading.showError("请输入有效金额");
      return;
    }

    if (_selectedMeter == null) {
      EasyLoading.showError("请选择电表");
      return;
    }
    EasyLoading.show();
    if (widget.arguments['type'] == 'electricity') {
      try {
        await electricityMeterApi.rechargeElectricityMeter({
          "electricityMeterId": _selectedMeter!['electricityMeterId'],
          "money": amount,
        });
        Future.delayed(const Duration(seconds: 2), () {
          EasyLoading.dismiss();
          EasyLoading.showSuccess("充值成功");
          // 更新
          _fetchMeterList(_selectedMeter!["number"]);
          Stacker.pop();
        });
      } catch (e) {
        EasyLoading.showError(e.toString());
      }
    }

    // taiDialog(
    //   context: context,
    //   child: Column(
    //     children: [
    //       Text("确认充值 ¥$amount ?"),
    //       const SizedBox(height: 16),
    //       TextField(
    //         obscureText: true,
    //         decoration: const InputDecoration(
    //           hintText: "请输入登录账号的密码",
    //           border: OutlineInputBorder(),
    //         ),
    //       ),
    //     ],
    //   ),
    //   onConfirm: (dialogContext) async {
    //     if (widget.arguments['type'] == 'electricity') {
    //       try {
    //         await electricityMeterApi.rechargeElectricityMeter({
    //           "electricityMeterId": _selectedMeter!['electricityMeterId'],
    //           "money": amount,
    //         });
    //         Future.delayed(const Duration(seconds: 2), () {
    //           EasyLoading.showSuccess("充值成功");
    //           // 更新
    //           _fetchMeterList(_selectedMeter!["number"]);
    //           Navigator.of(context).pop();
    //         });
    //       } catch (e) {
    //         EasyLoading.showError(e.toString());
    //       }
    //     }
    //     // TODO: 处理水费充值
    //   },
    // );
  }
} 